package com.mytest.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resources;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import com.mytest.dao.interfaces.StudentDao;
import com.mytest.entity.Student;
import com.mytest.utiltools.MyBatisUtil;

@Repository("studentDao")
public class StudentDaoImpl implements StudentDao {
	private static final Log log = LogFactory.getLog(StudentDaoImpl.class);
	private static final String studentMapper = "com.mytest.dao.StudentMapper";

	@Override
	public Map<String, Object> selectOne(int id) {
		SqlSession sqlSession = MyBatisUtil.getSqlSession();
		Map<String, Object> returnMap = null;
		try {
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			paramsMap.put("id", id);
			returnMap = sqlSession.selectOne(studentMapper + ".selectOne", paramsMap);
			return returnMap;
		} catch (Exception e) {
			return returnMap;
		}finally {
			sqlSession.close();
		}

	}

	@Override
	public List<Map<String, Object>> selectList(Student params) {
		SqlSession sqlSession = MyBatisUtil.getSqlSession();
		List<Map<String, Object>> returnlist = null;
		try {
			returnlist = sqlSession.selectList(studentMapper + ".selectList", params);
			log.error(returnlist);
			return returnlist;
		} catch (Exception e) {
			return returnlist;
		}finally {
			sqlSession.close();
		}
	}

	@Override
	public int insert(Student params) {
		SqlSession sqlSession = MyBatisUtil.getSqlSession(false);
		int result = 0;
		try {
			result = sqlSession.insert(studentMapper + ".insert", params);
			sqlSession.commit();
			return result;
		} catch (Exception e) {
			sqlSession.rollback();
			sqlSession.commit(true);
			return result;
		} finally {
			sqlSession.close();
		}
	}

	@Override
	public int update(Student params) throws Exception {
		SqlSession sqlSession = MyBatisUtil.getSqlSession(false);
		int result = 0;
		try {
			result = sqlSession.update(studentMapper + ".update", params);
			sqlSession.commit();
			return result;
		} catch (Exception e) {
			sqlSession.rollback();
			sqlSession.commit(true);
			return result;
		} finally {
			sqlSession.close();
		}
	}

	@Override
	public int delete(Map<String, Object> paramsMap) throws Exception {
		SqlSession sqlSession = MyBatisUtil.getSqlSession(false);
		int result = 0;
		try {
			result = sqlSession.delete(studentMapper + ".delete", paramsMap);
			sqlSession.commit();
			return result;
		} catch (Exception e) {
			sqlSession.rollback();
			return result;
		} finally {
			sqlSession.close();
		}
	}

}
